<template>
  <div class="bg-white rounded-xl shadow-lg p-6 max-w-6xl mx-auto transition-all duration-300">
    <!-- 使用Element UI表单组件 -->
    <el-form 
      :inline="true" 
      :model="formData" 
      class="mb-6"
      label-width="80px"
    >
      <el-form-item label="线体">
        <el-input 
          v-model="formData.threadNo" 
          prefix-icon="el-icon-search"
          placeholder="输入线体"
          clearable
        ></el-input>
      </el-form-item>
      
      <el-form-item label="工单">
        <el-input 
          v-model="formData.prodNo" 
          prefix-icon="el-icon-document"
          placeholder="输入工单"
          clearable
        ></el-input>
      </el-form-item>
      
      <!-- 开始时间选择器 -->
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          prefix-icon="el-icon-date"
        ></el-date-picker>
      </el-form-item>
      
      <!-- 结束时间选择器 -->
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          prefix-icon="el-icon-date"
        ></el-date-picker>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          @click="handleQuery" 
          type="primary"
          icon="el-icon-search"
          :loading="listLoading || chartLoading"
        >
          查询
        </el-button>
        <el-button 
          @click="clearInputs" 
          type="default"
          icon="el-icon-eraser"
          style="margin-left: 10px;"
        >
          清空
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 加载状态 -->
    <div v-if="listLoading && viewMode === 'list'" class="flex justify-center items-center py-12">
      <el-skeleton :loading="listLoading" effect="pulse" />
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="mb-6">
      <el-alert
        title="错误提示"
        type="error"
        :closable="false"
        :show-icon="true"
      >
        {{ error }}
      </el-alert>
    </div>

    <!-- 数据展示 -->
    <div v-if="(listData.length > 0 || chartStatsData.length > 0) && !error" class="mt-6">
      <!-- 视图切换器 -->
      <div class="flex justify-center mb-6">
        <el-radio-group v-model="viewMode" @change="handleViewModeChange">
          <el-radio-button label="list">
            <i class="fa fa-list mr-2"></i>列表视图
          </el-radio-button>
          <el-radio-button label="chart">
            <i class="fa fa-bar-chart mr-2"></i>图表视图
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'">
        <el-table
          :data="listData"
          stripe
          border
          highlight-current-row
          @row-click="selectItem"
          class="w-full"
        >
          <el-table-column prop="barcode" label="条形码" width="180"></el-table-column>
          <el-table-column prop="routeno" label="路线编号" width="120"></el-table-column>
          <el-table-column label="创建时间" width="200">
            <template #default="scope">
              {{ formatDateTime(scope.row.createddatetime) }}
            </template>
          </el-table-column>
          <el-table-column prop="prodno" label="生产编号" width="180"></el-table-column>
          <el-table-column prop="qty" label="数量" width="80" align="center"></el-table-column>
          <el-table-column prop="result" label="检测结果" width="120">
            <template #default="scope">
              <el-tag
                :type="scope.row.result === 'FAIL' ? 'danger' : 'success'"
                effect="plain"
              >
                {{ scope.row.result === 'FAIL' ? '不合格' : '合格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="threadno" label="线体编号" width="100"></el-table-column>
        </el-table>
        
        <!-- 分页控件 -->
        <div class="mt-4 flex justify-end">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 图表视图 -->
      <div v-if="viewMode === 'chart'" class="bg-white p-4 rounded-lg shadow-md transition-all duration-300">
        <div v-if="chartLoading" class="flex justify-center items-center h-[400px]">
          <el-icon class="is-loading" size="40">
            <Loading />
          </el-icon>
        </div>
        <div v-else-if="chartStatsData.length === 0" class="flex justify-center items-center h-[400px]">
          <el-empty description="暂无图表数据" />
        </div>
        <div v-else id="barChart" class="w-full h-[400px]"></div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!listLoading && !chartLoading && !error && listData.length === 0 && chartStatsData.length === 0" class="flex flex-col items-center justify-center py-12 text-center">
      <el-empty description="未找到数据">
        <template #image>
          <img src="https://picsum.photos/200/200?random=1" alt="空数据" class="w-20 h-20" />
        </template>
        <template #bottom>
          <el-button @click="clearInputs">重新输入</el-button>
        </template>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';

// 表单数据
const formData = ref({
  threadNo: '',
  prodNo: '',
  startTime: '',
  endTime: ''
});

// 状态管理
const listLoading = ref(false); // 列表数据加载状态
const chartLoading = ref(false); // 图表数据加载状态
const error = ref(null);
const viewMode = ref('list'); // 视图模式：list/chart

// 列表数据
const listData = ref([]);
const totalCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 图表专用统计数据（全量）
const chartStatsData = ref([]); // 格式: [{routeNo, passCount, failCount}, ...]

// 图表实例
let chartInstance = ref(null);
const selectedItem = ref(null);

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';
  const date = new Date(dateTimeString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 分页事件
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  fetchListData(); // 重新加载列表数据
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchListData();
};

// 处理查询（统一触发列表和图表数据更新）
const handleQuery = () => {
  // 表单验证
  if (!formData.value.threadNo && !formData.value.prodNo) {
    error.value = '请至少输入线体或工单';
    return;
  }
  if (formData.value.startTime && formData.value.endTime && new Date(formData.value.startTime) > new Date(formData.value.endTime)) {
    error.value = '开始时间不能大于结束时间';
    return;
  }

  error.value = '';
  // 根据当前视图模式加载对应数据
  if (viewMode.value === 'list') {
    currentPage.value = 1; // 重置分页
    fetchListData();
  } else {
    fetchChartStatsData();
  }
};

// 获取列表分页数据
const fetchListData = async () => {
  listLoading.value = true;
  try {
    const queryParams = new URLSearchParams();
    if (formData.value.threadNo) queryParams.append('threadNo', formData.value.threadNo);
    if (formData.value.prodNo) queryParams.append('prodNo', formData.value.prodNo);
    if (formData.value.startTime) queryParams.append('startTime', formData.value.startTime);
    if (formData.value.endTime) queryParams.append('endTime', formData.value.endTime);
    queryParams.append('page', currentPage.value);
    queryParams.append('pageSize', pageSize.value);

    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api';
    const url = `${baseUrl}/routejournal/search?${queryParams.toString()}`;

    const response = await fetch(url, {
      method: 'GET',
      credentials: import.meta.env.VITE_CORS_CREDENTIALS === 'true' ? 'include' : 'omit',
      headers: { 'Accept': 'application/json' }
    });

    if (!response.ok) throw new Error(`请求失败：${response.status}`);
    const result = await response.json();
    if (result.code !== 200) throw new Error(result.message || '获取列表数据失败');

    listData.value = result.data.records || [];
    totalCount.value = result.data.total || 0;
  } catch (err) {
    error.value = err.message || '获取列表数据异常';
    console.error('列表数据错误:', err);
  } finally {
    listLoading.value = false;
  }
};

// 获取图表全量统计数据（新增：专门用于图表的接口）
const fetchChartStatsData = async () => {
  chartLoading.value = true;
  try {
    const queryParams = new URLSearchParams();
    if (formData.value.threadNo) queryParams.append('threadNo', formData.value.threadNo);
    if (formData.value.prodNo) queryParams.append('prodNo', formData.value.prodNo);
    if (formData.value.startTime) queryParams.append('startTime', formData.value.startTime);
    if (formData.value.endTime) queryParams.append('endTime', formData.value.endTime);

    // 假设后端提供专门的统计接口（根据实际接口调整）
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api';
    //http://localhost:8080/api/routejournal/barChartThread?
    const url = `${baseUrl}/routejournal/barChartThread?${queryParams.toString()}`;

    const response = await fetch(url, {
      method: 'GET',
      credentials: import.meta.env.VITE_CORS_CREDENTIALS === 'true' ? 'include' : 'omit',
      headers: { 'Accept': 'application/json' }
    });

    if (!response.ok) throw new Error(`请求失败：${response.status}`);
    const result = await response.json();
    if (result.code !== 200) throw new Error(result.message || '获取统计数据失败');

    chartStatsData.value = result.data || [];
    updateChart(); // 数据获取后更新图表
  } catch (err) {
    error.value = err.message || '获取图表数据异常';
    console.error('图表数据错误:', err);
  } finally {
    chartLoading.value = false;
  }
};

// 视图模式切换处理
const handleViewModeChange = (newMode) => {
  if (newMode === 'chart') {
    // 切换到图表视图时加载全量统计数据
    if (chartStatsData.value.length === 0 || listData.value.length > 0) {
      fetchChartStatsData();
    } else {
      updateChart();
    }
  }
};

// 清空输入
const clearInputs = () => {
  formData.value = {
    threadNo: '',
    prodNo: '',
    startTime: '',
    endTime: ''
  };
  error.value = '';
  listData.value = [];
  totalCount.value = 0;
  chartStatsData.value = [];
  currentPage.value = 1;
  if (chartInstance.value) {
    chartInstance.value.clear();
  }
};

// 选择列表项
const selectItem = (item) => {
  selectedItem.value = item;
  ElMessage({
    message: `已选择: ${item.barcode} (${item.prodno})`,
    type: 'success',
    duration: 2000
  });
};

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('barChart');
  if (!chartDom) return;

  // 销毁旧实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  
  chartInstance.value = echarts.init(chartDom);
};

// 更新图表
const updateChart = async () => {
  if (chartStatsData.value.length === 0) return;

  try {
    await nextTick();
    initChart(); // 确保图表实例初始化

    // 提取图表数据
    const routeNos = chartStatsData.value.map(item => item.routeNo || '未知路线');
    const passData = chartStatsData.value.map(item => item.passCount || 0);
    const failData = chartStatsData.value.map(item => item.failCount || 0);

    // 图表配置
const option = {
  title: { text: '各路线检测结果统计', left: 'center', top: 10 },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    formatter: function(params) {
      const idx = params[0].dataIndex;
      const route = chartStatsData.value[idx];
      return `
        <div><strong>${route.routeNo}</strong></div>
        <div>合格: ${route.passCount || 0}</div>
        <div>不合格: ${route.failCount || 0}</div>
      `;
    }
  },
  legend: { data: ['合格', '不合格'], bottom: 10 },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '20%', // 增加底部空间
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: routeNos,
    axisLabel: {
      rotate: 45,
      interval: 0,
      fontSize: 10,
      formatter: function(value) {
        if (value.length > 6) {
          return value.substring(0, 6) + '...';
        }
        return value;
      }
    }
  },
  yAxis: { type: 'value', name: '数量', minInterval: 1 },
  series: [
    { name: '合格', type: 'bar', data: passData, itemStyle: { color: '#10b981' } },
    { name: '不合格', type: 'bar', data: failData, itemStyle: { color: '#ef4444' } }
  ],
  dataZoom: routeNos.length > 8 ? [
    { type: 'slider', xAxisIndex: 0, bottom: 5 }
  ] : []
};

    chartInstance.value.setOption(option);

    // 图表点击事件
    chartInstance.value.off('click');
    chartInstance.value.on('click', (params) => {
      if (params.seriesType === 'bar') {
        const routeNo = routeNos[params.dataIndex];
        showRouteDetails(routeNo);
      }
    });

  } catch (err) {
    ElMessage.error(`图表渲染失败: ${err.message}`);
    console.error('图表错误:', err);
  }
};

// 显示路线详情
const showRouteDetails = (routeNo) => {
  const route = chartStatsData.value.find(item => item.routeNo === routeNo);
  if (!route) return;

  ElMessageBox({
    title: `路线 ${routeNo} 详情`,
    message: `
      <div class="text-left">
        <p><strong>合格数量:</strong> <span style="color:#10b981">${route.passCount || 0}</span></p>
        <p><strong>不合格数量:</strong> <span style="color:#ef4444">${route.failCount || 0}</span></p>
        <p><strong>总计:</strong> ${(route.passCount || 0) + (route.failCount || 0)}</p>
      </div>
    `,
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  });
};

// 窗口大小变化处理
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
};

// 生命周期
onMounted(() => {
  formData.value.threadNo = '5-D';
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

// 监听图表数据变化自动更新
watch(chartStatsData, () => {
  if (viewMode.value === 'chart' && !chartLoading.value) {
    updateChart();
  }
});
</script>

<style scoped>
/* 关键：确保图表容器有明确的宽高，ECharts需要具体尺寸才能渲染 */
#barChart {
  width: 100% !important;
  height: 400px !important; /* 强制设置高度，避免被父元素挤压 */
  min-height: 400px;
}

/* 修复视图切换时的容器显示问题 */
:deep(.el-radio-button__inner) {
  padding: 8px 16px;
}

/* 确保加载状态容器高度一致 */
.chart-loading-container {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>